package com.zhuoyue.framework.aspectj;

import com.zhuoyue.common.annotation.LogTakep;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 日志注解切面类
 *
 * @author hewenze
 */
@Aspect
@Component
public class LogTakepAspect {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @After("@annotation(com.zhuoyue.common.annotation.LogTakep)")
    public void LogAspect1(JoinPoint point) throws Throwable {

        //获取token中的orgCode和Id
        // HttpServletRequest request = getHttpServletRequest();

        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        // 获取方法上面的注解
        LogTakep logTake = method.getAnnotation(LogTakep.class);
        // 获取操作描述的属性值
        String takeMessage = logTake.takeMessage();
        // String operationEvent = logTake.operationEvent();
        // 创建一个map(准备记录日志信息)
       /* Map<String,String> map = new HashMap<>();
        map.put("takeMessage",takeMessage);// 设置操作内容
        map.put("operationEvent",operationEvent);// 设置操作内容*/
        String hello = "hello";
        //将map发送至消息队列中
        //convertSendAndReceive() 方法会导致接口访问时间长至5s以上，所以用下面这个。
        this.rabbitTemplate.convertAndSend(hello, takeMessage);
    }

    private HttpServletRequest getHttpServletRequest() {
        //1.从header里面获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }
}


